	/* DS18s20 transaction sequence:(everytime)
	step1: initialization
		master:send reset_pulse
		slave:send presence_pulse{
			master.mode=output
			send 0 for minimum 480us
			master.mode=input
			after 15us-60us slave transmits low for 60us-240us 
			
		}
		
	step2: ROM Command
		read rom[33h]
	
	step3: DS18S20 Function Command
		convert T[44h]
		Read scratchpad[BEh]
		(send reset_pulse to finish after 
		reading byte0 and byte1)
		
		*/
#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>

#include "lcd.h"
#include "usart.h"

#define T_DDR DDRA
#define T_DQ 1
#define T_PORT PORTA
#define T_PIN PINA

#define T_READPIN (T_PIN & (1<<T_DQ))

#define T_INPUT T_DDR &= ~(1<<T_DQ)
#define T_OUTPUT T_DDR |= (1<<T_DQ)
#define T_HIGH T_PORT |= (1<<T_DQ)
#define T_LOW T_PORT &= ~(1<<T_DQ)
#define T_RESET T_LOW

#define T_CONVERT 0x44
#define T_READ 0xBE
#define T_SKIPROM 0xcc

unsigned char temp[2];
unsigned char count_remain, count_per_c;

unsigned char init_ds18s20(void){
/*initialization -- reset for 480uS*/
	T_OUTPUT;
	T_RESET;
	_delay_us(500);
	T_INPUT;
	_delay_us(60);
	if(T_READPIN!=0) return 0xff;
	_delay_us(420);
	return 0x00;
}

void write_byte(unsigned char byte){
	unsigned char i=0;
	for(i=0;i<8;i++){
	T_LOW;
	T_OUTPUT;
	_delay_us(1);
		if(byte&1){ //write 1
		T_INPUT;
		_delay_us(60);
		}
		else {	//write 0
			T_LOW;
			T_OUTPUT;			
			_delay_us(60);
			T_INPUT;
			}
	byte>>=1;
	}
	
}

unsigned char read_byte(void){
	unsigned char i=0,k=0;
	unsigned char j=0;
	
	for(j=0;j<8;j++){
	
	T_LOW;
	T_OUTPUT;
	_delay_us(1);
	T_INPUT;
	_delay_us(10);//15us
	
	if(T_READPIN) k|=(1<<7);
	if(j!=7)k>>=1;
	_delay_us(40);
	}
	
	return k;

}

void read_temp(void){
	unsigned char dummy;
	
	init_ds18s20();
	write_byte(T_SKIPROM);
	write_byte(T_CONVERT);
	_delay_ms(1);
	
	init_ds18s20();
	write_byte(T_SKIPROM);
	write_byte(T_READ);
	temp[0] = read_byte();
	temp[1] = read_byte();
	dummy = read_byte();
	dummy = read_byte();
	dummy = read_byte();
	dummy = read_byte();
	count_remain = read_byte();
	count_per_c = read_byte();
	init_ds18s20();
	
}

int main(void){

	lcd_init(LCD_DISP_ON);
	USART_init();
	DDRC=0xff;
	PORTC=0x00;
	

	while(1){
	
		read_temp();
		temp[0]/=2;
		USART_Transmit('0'+temp[0]/10);
		USART_Transmit('0'+temp[0]%10);
		PORTC=temp[0];
		USART_Transmit(' ');
		USART_Transmit('0'+temp[1]/10);
		USART_Transmit('0'+temp[1]%10);
		
		USART_Transmit(' ');
		USART_Transmit('0'+count_remain/10);
		USART_Transmit('0'+count_remain%10);
				
		USART_Transmit(' ');
		USART_Transmit('0'+count_per_c/10);
		USART_Transmit('0'+count_per_c%10);
		
		USART_Transmit('|');
		_delay_ms(200);
		
	}
return 0;
}

	
	